﻿// Copyright (c)  YISH. All rights reserved.
// Licensed under the MIT License, See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Linq;
using NSQL.Sharpen;

namespace NSQL.Expressions
{
    public class MatchPair<TWhen, TThen>
    {
        public TWhen When { get; set; }
        public TThen Then { get; set; }
    }

    public class SimpleMatchExpression : BaseExpression, ISimpleMatchExpression
    {
        public IExpression Comparison { get; set; }

        public IList<MatchPair<IExpression, IExpression>> Matches { get; } =
            new List<MatchPair<IExpression, IExpression>>();

        public IExpression Default { get; set; }

        public SimpleMatchExpression()
        {
        }

        public SimpleMatchExpression(IExpression expression,
            IEnumerable<MatchPair<IExpression, IExpression>> matches, IExpression @default)
        {
            Comparison = expression;
            foreach (var match in matches)
            {
                Matches.Add(match);
            }

            Default = @default;
        }

        public override T Accept<T>(IExpressionVisitor<T> visitor) => visitor.Visit(this);
        public override void Accept(IExpressionVisitor visitor) => visitor.Visit(this);

        public override bool IsValid =>
            Default.IsValid && Comparison.IsValid && Matches.All(o => o.Then.IsValid && o.When.IsValid);

        protected override IExpression DeepCopy()
        {
            return new SimpleMatchExpression(Comparison.DeepClone(), Matches.Select(o => new MatchPair<IExpression, IExpression>()
            {
                When = o.When.DeepClone(),
                Then = o.Then.DeepClone()
            }), Default.DeepClone())
            {
                Tag = Tag
            };
        }
    }
}